import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { useRequest } from '@umijs/hooks';
import { Card, Input, Button, Select, Icon, InputNumber, Tooltip, DatePicker, message } from 'antd';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  Const
} from '../Const';
import {
  createUnderchargeAccident,
  getPkgAccidentDetail,
  updateUnderchargeAccident
} from './service';

import AuthComponent from '@/components/Authorized/AuthComponent';
import CTSelect from '../addEditIncident/components/CTSelect';

const FormItem = Form.Item;
const { Option } = Select;

class PrivateData {
  static CTTypeMap = new Map()
    .set(1, 'pkgColor')
    .set(2, 'pkgType')
    .set(3, 'pkgContent');
  static pkgId = '';
}

const AddEditIncidentMore = props => {

  const { location: { state }, form } = props;

  const [itemData, setItemData] = useState({});

  const [CTSelectVisible, setCTSelectVisible] = useState(false); // 颜色、类别、描述弹窗
  const [CTType, setCTType] = useState(''); // 类型 1color 2category 3desc
  const [CTVal, setCTVal] = useState(''); // 值

  const goBackList = useCallback(() => {
    let urlObj = {
      2: '/inPortBaggageManagement/lessBaggageManagement',
      1: '/inPortBaggageManagement/damagedBaggageManagement',
      6: '/inPortBaggageManagement/internalMissingManagement',
      3: '/inPortBaggageManagement/moreBaggageManagement',
    }
    // 是否来自监控页
    if (state?.isFromQuickRetrieval) {
      router.push({
        pathname: Const.commonUrl + '/systemIndex',
      });
    } else {
      router.push({
        pathname: Const.commonUrl + urlObj[state.ownerType],
      });
    }
  }, [state]);

  // 获取详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取详情');
      let data = res.pkgAccidentDetailInfoVo || {}
      let pkgDetailInfoList = data.pkgDetailInfoList || [];
      let pkgDetailInfoListItem = pkgDetailInfoList[0]; // 多收只有一个行李
      if (pkgDetailInfoList.length >= 1) {
        data.pkgProperty = pkgDetailInfoListItem.pkgProperty || '';
        data.pkgColor = pkgDetailInfoListItem.pkgColor || '';
        data.pkgType = pkgDetailInfoListItem.pkgType || '';
        data.pkgContent = pkgDetailInfoListItem.pkgContent || '';
        data.wtCode = pkgDetailInfoListItem.wtCode || '';
        data.pkgNo = pkgDetailInfoListItem.pkgNo || '';
      }
      PrivateData.pkgId = pkgDetailInfoListItem.id;
      setItemData(data);
    }
  });

  // 创建事故单
  const { run: runCreateUnderchargeAccident, loading: addLoading } = useRequest(data => createUnderchargeAccident(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '创建事故单');
      goBackList()
    }
  });

  // 编辑事故单
  const { run: runUpdateUnderchargeAccident, loading: editLoading } = useRequest(data => updateUnderchargeAccident(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '编辑事故单');
      goBackList();
    }
  });

  useEffect(() => {
    if (state.type === 'edit' && state.accidentId) {
      runGetPkgAccidentDetail({
        accidentId: state.accidentId || ''
      });
    }
    if (state.type === 'add') {
      PrivateData.pkgId = '';
      setItemData(state.itemData);
    }
  }, [state]);

  // 颜色、类别、描述弹窗 - 关闭
  const CTSelectClose = useCallback(() => {
    setCTSelectVisible(false);
  }, []);
  // 颜色、类别、描述弹窗 - 打开
  const CTSelectOpen = useCallback((type) => {
    let val = form.getFieldValue(PrivateData.CTTypeMap.get(type)) || '';
    if (type === 3) {
      if (!val) {
        val = ['', '', ''];
      } else {
        val = val.split(',');
      }
    }
    setCTVal(val);
    setCTType(type);
    setCTSelectVisible(true);
  }, []);
  // 颜色、类别、描述弹窗 - 取消
  const CTSelectCancel = useCallback(() => {
    CTSelectClose();
  }, []);
  // 颜色、类别、描述弹窗 - 提交
  const CTSelectSubmit = useCallback(val => {
    let _val = PrivateData.CTTypeMap.get(CTType);
    form.setFieldsValue({
      [_val]: CTType === 3 ? val.join(',') : val
    });
    CTSelectClose();
  }, [CTType]);

  // 禁用今天之后的时间
  const disabledDate = useCallback((current) => {
    return current && current > moment().endOf('day');
  }, []);

  // 航班号 - 校验
  const flightDateValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (/^[0-9A-Za-z]{5,6}$/.test(value)) {
        callback();
      } else {
        callback('输入错误，请认真核对');
      }
    } else {
      callback('')
    }
  }, []);

  // 证件号 - 验证
  const idNoValidator = useCallback((rule, value, callback) => {
    let idType = form.getFieldValue('idType');
    if (value) {
      Const.idNoValidator(idType, value, callback);
    } else {
      callback();
    }
  }, [form]);

  // 防止重复提交
  const saveFormStatus = useMemo(() => {
    return (addLoading || editLoading);
  }, [addLoading, editLoading]);

  const saveForm = useCallback(() => {
    if (saveFormStatus) {
      message.warning('请勿重复提交');
      return;
    }
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.pkgFlightDate && fieldsValue.pkgFlightDate.isValid()) {
        fieldsValue.pkgFlightDate = moment(fieldsValue.pkgFlightDate).format(Const.format);
      }
      let pkgDetailInfoDtoList = [];
      pkgDetailInfoDtoList.push({
        pkgProperty: fieldsValue.pkgProperty || '',
        pkgColor: fieldsValue.pkgColor || '',
        pkgType: fieldsValue.pkgType || '',
        pkgContent: fieldsValue.pkgContent || '',
        wtCode: fieldsValue.wtCode || '',
        pkgNo: fieldsValue.pkgNo || '',
      });
      fieldsValue.pkgDetailInfoDtoList = pkgDetailInfoDtoList;
      const isAuth = AuthComponent.getAuth(Const.permissionsType.get(+state.ownerType) + '.changeAllIncident') ? 1 : 0;
      if (state.type === 'add') {
        runCreateUnderchargeAccident({
          ...fieldsValue,
          paxId: state.itemData?.paxId,
          accidentType: state.ownerType,
          flightNo: fieldsValue.pkgFlightNo || '',
          flightDate: fieldsValue.pkgFlightDate || '',
          operateType: 1, // 0草稿 1提交
        });
      } else {
        fieldsValue.pkgDetailInfoDtoList[0].id = PrivateData.pkgId;
        fieldsValue.pkgDetailInfoDtoList[0].accidentId = state.accidentId;
        runUpdateUnderchargeAccident({
          ...fieldsValue,
          paxId: itemData?.paxId,
          accidentId: state.accidentId,
          accidentType: state.ownerType,
          operateType: 1, // 0草稿 1提交
          isAuth
        });
      }
    });
  }, [form, state, saveFormStatus, itemData]);

  return (
    <div className={styles.addEditIncidentMoreContent}>
      <Card title="必填信息" style={{ width: '100%' }}>
        <div className={styles.formContent}>
          <FormItem label="行李属性">
            {form.getFieldDecorator('pkgProperty', {
              rules: [
                { required: true, message: '请选择行李属性' }
              ],
              initialValue: itemData.pkgProperty || ''
            })(
              <Select
                allowClear
                placeholder="请选择"
                style={{ width: '100%' }}
              >
                {Const.pkgPropertyList.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="行李颜色(CT)">
            {form.getFieldDecorator('pkgColor', {
              rules: [
                { required: true, message: '请选择行李颜色' }
              ],
              initialValue: itemData.pkgColor || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(1)} />
                } />
            )}
          </FormItem>
          <FormItem label="行李类别(CT)">
            {form.getFieldDecorator('pkgType', {
              rules: [
                { required: true, message: '请选择行李类别' }
              ],
              initialValue: itemData.pkgType || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(2)} />
                } />
            )}
          </FormItem>
          <FormItem label="行李描述">
            {form.getFieldDecorator('pkgContent', {
              rules: [],
              initialValue: itemData.pkgContent || ''
            })(
              <Input
                placeholder="请输入"
                readOnly
                suffix={
                  <Icon type="diff" onClick={() => CTSelectOpen(3)} />
                } />
            )}
          </FormItem>
          <FormItem label="WT编号">
            {form.getFieldDecorator('wtCode', {
              rules: [],
              initialValue: itemData?.wtCode || ''
            })(
              <Input placeholder="请输入" maxLength={50} />
            )}
          </FormItem>
        </div>
      </Card>
      <Card title="重要信息" style={{ width: '100%' }}>
        <div className={styles.formContent}>
          <FormItem label="旅客姓名">
            {form.getFieldDecorator('paxName', {
              rules: [],
              initialValue: itemData?.paxName || ''
            })(
              <Input placeholder="请输入" disabled={itemData?.paxName} maxLength={50} />
            )}
          </FormItem>
          <FormItem label="航班号">
            {form.getFieldDecorator('pkgFlightNo', {
              rules: [
                { validator: flightDateValidator }
              ],
              initialValue: itemData?.flightNo || ''
            })(
              <Input
                placeholder="3U"
                suffix={
                  <Tooltip title="例AA123、AA1234、AA123A、AA1234A、MF8943A、3U234">
                    <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                  </Tooltip>
                }
                disabled={itemData?.flightNo}
                maxLength={6} />
            )}
          </FormItem>
          <FormItem label="航班日期">
            {form.getFieldDecorator('pkgFlightDate', {
              rules: [],
              initialValue: itemData?.flightDate ? moment(itemData?.flightDate) : moment()
            })(
              <DatePicker
                style={{ width: '100%' }}
                format={Const.format}
                disabled={itemData?.flightDate}
                disabledDate={disabledDate}
              />
            )}
          </FormItem>
          <FormItem label="行李总重量">
            {form.getFieldDecorator('tktPkgWeight', {
              rules: [],
              initialValue: itemData?.pkgWeight || ''
            })(
              <InputNumber
                step={0.01}
                placeholder="请输入"
                disabled={itemData?.pkgWeight}
                min={0}
                max={Const.inputNumMax}
                style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem label="行李号">
            {form.getFieldDecorator('pkgNo', {
              rules: [
                { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
              ],
              initialValue: itemData?.pkgNo || ''
            })(
              <Input placeholder="请输入" maxLength={10} disabled={itemData?.pkgNo} />
            )}
          </FormItem>
          <FormItem label="客票号">
            {form.getFieldDecorator('tktNo', {
              rules: [
                { pattern: /^\d{13}$/, message: '请输入13位数字' },
              ],
              initialValue: itemData?.tktNo || ''
            })(
              <Input placeholder="请输入" maxLength={13} disabled={itemData?.tktNo} />
            )}
          </FormItem>
          <FormItem label="证件类型">
            {form.getFieldDecorator('idType', {
              rules: [],
              initialValue: Const.dealIdType(itemData?.idType)
            })(
              <Select
                allowClear
                placeholder="请选择"
                disabled={itemData?.idType}
                style={{ width: '100%' }}
              >
                {Const.idTypeListForSearch.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="证件号">
            {form.getFieldDecorator('idNo', {
              rules: [
                { validator: idNoValidator }
              ],
              initialValue: itemData?.idNo || ''
            })(
              <Input placeholder="请输入" disabled={itemData?.idNo} maxLength={18} />
            )}
          </FormItem>
          <FormItem label="旅客航程">
            {form.getFieldDecorator('segment', {
              rules: [
                { pattern: /^[A-Z]{3}-([A-Z]{3}-)?[A-Z]{3}$/, message: '请输入正确格式' },
              ],
              initialValue: itemData?.segment || ''
            })(
              <Input
                placeholder="请输入"
                suffix={
                  <Tooltip title="例XMN-FOC,XMN-PEK-FOC">
                    <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                  </Tooltip>
                }
                maxLength={11}
                disabled={itemData?.segment} />
            )}
          </FormItem>
          <FormItem label="少收编号">
            {form.getFieldDecorator('underchargeAccidentId', {
              rules: [],
              initialValue: state?.type === 'add' ? (state?.lessInfoListId || '') : (itemData.underchargeAccidentId || '')
            })(
              <Input placeholder="请输入" maxLength={50} disabled={state?.type === 'add' ? (state?.lessInfoListId || '') : (itemData.underchargeAccidentId || '')} />
            )}
          </FormItem>
        </div>
      </Card>
      <div className={styles.btnBox}>
        <Button onClick={()=> router.goBack()} style={{ marginRight: '10px' }}>返回</Button>
        <Button type="primary" onClick={()=> saveForm()}>保存</Button>
      </div>
      <CTSelect
        modalVisible={CTSelectVisible}
        onCancel={CTSelectCancel}
        onSubmit={CTSelectSubmit}
        CTType={CTType}
        CTVal={CTVal}
      ></CTSelect>
    </div>
  )
};

export default Form.create()(AddEditIncidentMore);
